package com.mongodb.mongodbboot.config;

import cn.hutool.core.collection.CollectionUtil;
import com.mongodb.ConnectionString;
import com.mongodb.mongodbboot.model.TableStrategy;
import com.mongodb.mongodbboot.property.MongoProperty;
import com.mongodb.mongodbboot.property.MongoShard;
import com.mongodb.mongodbboot.service.ConfigQueryService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分库分表查询实现类
 *
 * @author zbb
 * @date 2021-08-11 13:00
 */
@Component
public class MongoShardingConfig implements InitializingBean {

    private static Date changeTime;
    public final Integer BATCH_SIZE = 10000;

    public static Map<String, MongoTemplate> mongoClientMap = new HashMap<>();

    public static Map<String, TableStrategy> tableStrategy = new HashMap<>();

    public static Map<String, Object> cacheTableMap = new HashMap<>();

    //历史库连接
    private MongoTemplate HistoryMongoTemplate;

    public MongoTemplate getHistoryMongoTemplate() {
        return HistoryMongoTemplate;
    }

    //缓存库
    private MongoTemplate cacheMongoTemplate;

    public MongoTemplate getCacheMongoTemplate() {
        return cacheMongoTemplate;
    }

    /**
     * 查询配置信息服务层
     */
    @Autowired
    private ConfigQueryService configQueryService;
    /**
     * 配置信息
     */
    @Autowired
    private MongoProperty mongoLinkConfig;

    /**
     * 判断是否开始使用分库分表
     *
     * @param tableStrategy
     * @return
     */
    public boolean isSharding(TableStrategy tableStrategy, Date beginTime, Date endTime) {
        //侧率分库分表优先处理
        if (tableStrategy != null && tableStrategy.getShardingYet() == 1) {
            return true;
        }
        //查询的开始或者结束时间大于开始分库分表的时间
        if (changeTime != null && (beginTime.compareTo(changeTime) >= 0 || endTime.compareTo(changeTime) >= 0)) {
            return true;
        }

        return false;
    }

    /**
     * 是否历史库
     *
     * @param tableStrategy
     * @param beginTime
     * @param endTime
     * @return
     */
    public boolean isHistory(TableStrategy tableStrategy, Date beginTime, Date endTime) {
        //无分库分表配置
        if (tableStrategy == null) {
            return true;
        }
        //查询的开始或者结束时间大于开始分库分表的时间
        if (tableStrategy != null && tableStrategy.getShardingYet() != 1 && changeTime != null && (beginTime.compareTo(changeTime) < 0 || endTime.compareTo(changeTime) < 0)) {
            return true;
        }
        return false;
    }

    /**
     * 获取分库分表的查询时间
     *
     * @param beginTime
     * @return
     */
    public Date findShardingBeginTime(TableStrategy tableStrategy, Date beginTime) {
        //侧率分库分表优先处理
        if (tableStrategy != null && tableStrategy.getShardingYet() == 1) {
            return new Date(beginTime.getTime());
        }
        //如果查询时间小于分库分表的开始时间，则查询开始时间为分库分表时间
        if (changeTime != null && beginTime.compareTo(changeTime) < 0) {
            return changeTime;
        }
        return new Date(beginTime.getTime());
    }

    /**
     * 获取历史库查询结束时间
     *
     * @param tableStrategy
     * @param endTime
     * @return
     */
    public Date findHistoryEndTime(TableStrategy tableStrategy, Date endTime) {
        //侧率分库分表优先处理
        if (tableStrategy == null) {
            return new Date(endTime.getTime());
        }
        //如果结束时间大于分库分表时间，则查询结束时间为分库分表时间
        if (changeTime != null && endTime.compareTo(changeTime) > 0) {
            return changeTime;
        }
        return new Date(endTime.getTime());
    }

    /**
     * 初始化分库分表数据库
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {

        changeTime = configQueryService.getShardingChangeTime();

        //获取所有的分表策略
        List<TableStrategy> list = configQueryService.getTableStrategy();
        for (TableStrategy strategy : list) {
            tableStrategy.put(strategy.getTableName(), strategy);
        }

        List<MongoShard> shardingLinks = mongoLinkConfig.getShardingLinks();
        if(CollectionUtil.isNotEmpty(shardingLinks)){
            for (MongoShard link : shardingLinks) {
                if (!"1".equals(link.getEnable())) {
                    continue;
                }
                ConnectionString connectionString = new ConnectionString(link.getUrl());
                SimpleMongoClientDatabaseFactory mongoClientDbFactory = new SimpleMongoClientDatabaseFactory(connectionString);
                MongoTemplate mongoTemplate = new MongoTemplate(mongoClientDbFactory);
                mongoClientMap.put(link.getAlias(), mongoTemplate);
            }
        }


        ConnectionString connectionString = new ConnectionString(mongoLinkConfig.getUri());
        SimpleMongoClientDatabaseFactory mongoClientDbFactory = new SimpleMongoClientDatabaseFactory(connectionString);
        HistoryMongoTemplate = new MongoTemplate(mongoClientDbFactory);

        //如果配置了缓冲库
        List<Map<String, Object>> cacheTableList = configQueryService.getCacheConfig();
        if (cacheTableList != null && cacheTableList.size() > 0) {
            cacheTableList.forEach(c -> {
                cacheTableMap.put(c.get("parm_name").toString(), c.get("parm_value"));
            });
            ConnectionString cacheConnectionString = new ConnectionString(mongoLinkConfig.getCacheUrl());
            SimpleMongoClientDatabaseFactory cacheMongoDbFactory = new SimpleMongoClientDatabaseFactory(cacheConnectionString);
            cacheMongoTemplate = new MongoTemplate(cacheMongoDbFactory);
        }
    }


}
